import "@ethersproject/shims";
import { ethers } from 'ethers';
import { global } from '@/config/config'
import { getValue } from "../deviceStorage";

const httpsProvider = new ethers.providers.JsonRpcProvider(global.RPCNode);

//获得执行交易ABI.
export const getExecTransactionABI = (to, value, safeTxGas, signature) => {
    //主合约的execTransaction功能.
    const masterABI = ["function execTransaction(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, bytes signatures)"]
    const masterIface = new ethers.utils.Interface(masterABI);
    const masterAbi = masterIface.encodeFunctionData("execTransaction", [to, value, global.EMPTY_DATA, 0, safeTxGas, 0, 0, global.ZERO_ADDRESS, global.ZERO_ADDRESS, signature]);
    return masterAbi;
}

//估计所需Gas.
export const estimateGasExecTransaction = async (to, value, safeTxGas, signature) => {
    const data_ = getExecTransactionABI(to, value, global.EMPTY_DATA, 0, safeTxGas, 0, 0, global.ZERO_ADDRESS, global.ZERO_ADDRESS, signature);
    const estimateGas = await httpsProvider.estimateGas({
        to: PROXY_ADDRESS,
        data: data_
    })
    return estimateGas;
}

export const ethSafeSign1_1 = async (transcationDetail, mnemonicStr, customFeeData) => {
    const to = transcationDetail.txInfo?.direction === 'OUTGOING' ? transcationDetail.txInfo?.recipient?.value : transcationDetail.txInfo?.sender?.value
    const value = transcationDetail.txInfo?.transferInfo?.value
    const safeTxGas = transcationDetail.detailedExecutionInfo?.safeTxGas
    const signature = transcationDetail.detailedExecutionInfo?.confirmations[0]?.signature
    const inputData = getExecTransactionABI(to, value, safeTxGas, signature);
    const feeData = customFeeData && customFeeData.feeData ? customFeeData.feeData : await httpsProvider.getFeeData();
    const gasConsume = customFeeData && customFeeData.gasConsume ? customFeeData.gasConsume : await estimateGasExecTransaction(to, value, safeTxGas, signature);
    const txInfo = {
        toAddress: transcationDetail.safeAddress,
        feeData,
        gasConsume,
        inputData
    }
    const txHash = await ethSafeTransfer(mnemonicStr, txInfo)
    return txHash
}

export const ethSafeReject1_1 = async (transcationDetail, mnemonicStr, customFeeData) => {
    const to = transcationDetail.txInfo?.to?.value
    const value = transcationDetail.txInfo?.value
    const safeTxGas = transcationDetail.detailedExecutionInfo?.safeTxGas
    const signature = transcationDetail.detailedExecutionInfo?.confirmations[0]?.signature
    const inputData = getExecTransactionABI(to, value, safeTxGas, signature);
    const feeData = customFeeData && customFeeData.feeData ? customFeeData.feeData : await httpsProvider.getFeeData();
    const gasConsume = customFeeData && customFeeData.gasConsume ? customFeeData.gasConsume : await estimateGasExecTransaction(to, value, safeTxGas, signature);
    const txInfo = {
        toAddress: transcationDetail.safeAddress,
        feeData,
        gasConsume,
        inputData
    }
    const txHash = await ethSafeTransfer(mnemonicStr, txInfo)
    return txHash
}

export const ethSafeTransfer = async (mnemonicStr, txInfo) => {
    let chainId = getValue('chainId')
    let selectedWallet = getValue('selectedWallet')
    const wallet = ethers.Wallet.fromMnemonic(mnemonicStr, selectedWallet.wallet_name) //助记词恢复钱包
    const nonce = await httpsProvider.getTransactionCount(wallet.address);
    const tx = {
        type: 2,
        nonce,
        to: txInfo.toAddress,
        maxPriorityFeePerGas: txInfo.feeData["maxPriorityFeePerGas"], // Recommended maxPriorityFeePerGas
        maxFeePerGas: txInfo.feeData["maxFeePerGas"], // Recommended maxFeePerGas
        value: '0x0',  // Send eth number
        gasLimit: txInfo.gasConsume, // Basic transaction costs exactly 21000
        data: txInfo.inputData, //Input data.
        chainId // Ethereum network id, this is goerli id
    };
    // 签署交易.
    const signedTx = await wallet.signTransaction(tx);
    const txHash = ethers.utils.keccak256(signedTx);
    console.log("Precomputed txHash:", txHash);
    // //发送交易.
    httpsProvider.sendTransaction(signedTx)
    return txHash
};